package fr.cephb.berkeley;

import com.sleepycat.db.Cursor;
import com.sleepycat.db.Database;
import com.sleepycat.db.Environment;

import fr.cephb.lang.Endian;

/**
 * static utilities for BerkeleyDB
 * @author lindenb
 *
 */
public class DBUtils {
	
/** close a Database without throwing an exception */
public static void safeClose(Database db)
	{
	if(db==null) return; 
	try {
		db.close();
		} 
	catch (Exception e) {
		
		}
	}		

/** close an Environment without throwing an exception */
public static void safeClose(Environment env)
	{
	if(env==null) return; 
	try {
		env.close();
		} 
	catch (Exception e) {
		
		}
	}	

/** close an Cursor without throwing an exception */
public static void safeClose(Cursor cursor)
	{
	if(cursor==null) return; 
	try {
		cursor.close();
		} 
	catch (Exception e) {
		
		}
	}

/** @deprecated please use a {@link ByteWriter} */
public static byte[] int32ToBytes(int value)
	{
	
	byte b[]=new byte[4];
	if(Endian.getDefault()==Endian.CEPH)
		{
		b[0] = (byte) (value >>> 24);
	    b[1] = (byte) (value >>> 16);
	    b[2] = (byte) (value >>>  8);
	    b[3] = (byte) (value       );
		}
	else
		{
		b[3] = (byte) (value >>> 24);
	    b[2] = (byte) (value >>> 16);
	    b[1] = (byte) (value >>>  8);
	    b[0] = (byte) (value       );
		}
	return b;
	}

/** @deprecated please use a {@ ByteReader} */
public static byte[] int64ToBytes(long value)
	{
	throw new UnsupportedOperationException("boum");
	}


/** convert a string to an array of bytes ending with a '\0' */
public static byte[] string2CString(String s)
	{
	byte array[]=s.getBytes();
	byte array2[]=new byte[array.length+1];
	System.arraycopy(array,0 , array2, 0, array.length);
	array2[array.length]=0;
	return array2;
	}

}
